//
// Created by Felix on 24-4-26.
//

#ifndef GAZE_AUTHHANDLER_HPP
#define GAZE_AUTHHANDLER_HPP

#include "oatpp/web/server/handler/AuthorizationHandler.hpp"
#include "oatpp/core/Types.hpp"

#include "common.hpp"
#include "service/AuthService.hpp"

class AuthHandler : public oatpp::web::server::handler::BearerAuthorizationHandler {
public:
    struct Payload : public oatpp::web::server::handler::AuthorizationObject {
        oatpp::Int32 userId;
        oatpp::String token;
    };
private:
    AuthService iAuthService;
public:
    AuthHandler() : oatpp::web::server::handler::BearerAuthorizationHandler("API" /* Realm */) {}

    std::shared_ptr<AuthHandler::AuthorizationObject> authorize(const oatpp::String &token) override {
        auto bearer_token = AuthHandler::token(token);
        if (bearer_token->empty())return nullptr;

        auto userDto = iAuthService.getUserByToken(bearer_token);
        auto payload = std::make_shared<Payload>();
        payload->userId = userDto->userId;
        payload->token = bearer_token;

        return payload;
    }

    static oatpp::String token(const oatpp::String &token) {
        if (!token) return "";

        std::string mutableToken = token;
        trim(mutableToken);
        if (mutableToken.empty()) return "";

        std::vector<std::string> result = splitAndRemoveEmpty(mutableToken);
        if (result[0] != "Bearer") return "";
        if (result[1].empty()) return "";

        return result[1];
    }
};

#endif //GAZE_AUTHHANDLER_HPP
